import { Injectable, Logger } from '@nestjs/common';
import { CreateToyItemDto } from './dto/create-toy-item.dto';
import { UpdateToyItemDto } from './dto/update-toy-item.dto';
import { UserToyItem } from '../../dao/UserToyItem';
import { FactoryToyItem } from '../../dao/FactoryToyItem';
import sequelize from '../../util/sequelize';
import { uuid } from 'uuidv4';
import { CommonResult } from '../../util/commonResult';

@Injectable()
export class ToyItemService {
  private userToyItem: typeof UserToyItem;
  private readonly factoryToyItem: typeof FactoryToyItem;

  constructor() {
    this.userToyItem = UserToyItem.initModel(sequelize);
    this.factoryToyItem = FactoryToyItem.initModel(sequelize);
    this.userToyItem.belongsTo(this.factoryToyItem, {
      foreignKey: 'toyId',
      targetKey: 'id',
      as: 'toyItem',
    });
  }

  async create(createToyItemDto: CreateToyItemDto, userInfo: any) {
    await this.userToyItem.findOrCreate({
      where: {
        userId: userInfo.userId,
        toyId: createToyItemDto.toyId,
      },
      defaults: {
        id: uuid(),
        userId: userInfo.userId,
        toyId: createToyItemDto.toyId,
      },
    });
    return CommonResult.success();
  }

  findAll() {
    return `This action returns all toyItem`;
  }

  async getItemList(createToyItemDto: CreateToyItemDto, userInfo: any) {
    if (!userInfo?.userId) {
      return CommonResult.failed('无用户信息');
    }

    const res = await this.userToyItem.findAll({
      attributes: ['id', 'createdTime'],
      where: {
        userId: userInfo.userId,
      },
      order: [['createdTime', 'DESC']],
      include: [
        {
          model: this.factoryToyItem,
          attributes: {
            exclude: ['createdTime', 'updatedTime', 'factoryId'],
          },
          as: 'toyItem',
        },
      ],
    });
    Logger.log(res);
    return CommonResult.success(res);
  }

  update(id: number, updateToyItemDto: UpdateToyItemDto) {
    return `This action updates a #${id} toyItem`;
  }

  remove(id: number) {
    return `This action removes a #${id} toyItem`;
  }
}
